/*
  混入页面的脚本，以操作当前页面DOM
  最后修改： 2023-2-6
*/
import dayjs from 'dayjs'
import G from './gauth.js'
import { _fetch } from '@/background/background-utils.js'

function _customScript(action, _) {
  console.log(action)
  const { func } = action
  func(document)
  return true
}

function _addAllLine() {
  document.querySelectorAll('*').forEach((e) => {
    e.style.outline = '1px solid #0093a8'
    return true
  })
}

function _removeAllLine() {
  document.querySelectorAll('*').forEach((e) => {
    e.style.outline = ''
    return true
  })
}

function _getCookie(key) {
  var reg = new RegExp(`(^| )${key}=([^;]*)(;|$)`)
  var arr = document.cookie.match(reg)
  return arr ? unescape(arr[2]) : null
}

function _updatePassword({ type, user, pwd }) {
  document.getElementById('password').attributes.type.value = ''
  if (type != 'manual') user = document.getElementById('username').value
  if (type == 'autoWith2021') {
    pwd = `pkpm2021${dayjs().format('YYYYMMDDHH')}${user}`
  } else if (type == 'auto') {
    pwd = `pkpm${dayjs().format('YYYYMMDDHH')}${user}`
  }
  document.getElementById('username').value = user
  document.getElementById('password').value = pwd
  return true
}

// 通用页面处理
async function normalProcess(url) {
  if (document.getElementById('password') && document.getElementById('username')) {
    const res = await chrome.runtime.sendMessage({
      action: 'bgRequest',
      params: { url: `pullObs?name=IdAutoEnterRule` },
    })
    // console.log('####res', res.data)
    if (!res.data) return
    const IdAutoEnterRule = JSON.parse(res.data)
    const resMatch = IdAutoEnterRule.reduce(
      (pre, cur) => {
        if (url.indexOf(cur.site) > -1) {
          const activeAccount = cur.accountLis.find((e) => e.active)
          console.log('activeAccount', activeAccount)
          pre = { success: true, ...activeAccount }
        }
        return pre
      },
      { success: false }
    )

    let account = 'xtgly'
    // window.dd = dayjs
    const nowTime = dayjs().format('YYYYMMDDHH')
    let password = `pkpm2021${nowTime}xtgly`
    if (resMatch.success) {
      account = resMatch.account
      password = resMatch.password.replace(/\{now\}/g, nowTime)
    }
    document.getElementById('username').value = account
    document.getElementById('password').value = password
    document.getElementById('password').attributes.type.value = ''
  }
}

var rules = {
  'csdn.net': () => {
    let adv = document.getElementsByClassName('toolbar-advert')
    if (adv.length > 0) adv[0].remove()
    if (_getCookie('blog_details_concision') != 0) {
      document.cookie = 'blog_details_concision=0;domain=csdn.net'
      window.location.reload()
    }
    return true
  },
  'www.it1352.com': () => {
    if (_getCookie('olduser') != 1) {
      document.cookie = 'olduser=1'
      window.location.reload()
    }
    return true
  },
  'zhihu.com': () => {
    let modals = document.getElementsByClassName('Modal-wrapper')
    if (modals.length > 0) modals[0].remove()
    return true
  },
  '192.168.2.24:8443': () => {
    console.log('is jump server')
    if (document.getElementById('id_username')) {
      document.getElementById('id_username').value = '肖克俊'
      document.getElementById('password').value = '@Hh112233'
    }

    if (document.getElementsByName('otp_code').length > 0) {
      document.getElementsByName('otp_code')[0].value = G.generate('2CTBAHHLKJGAORQT')
    }
    return true
  },
  'ops.hunanjianyan.com': () => {
    console.log('is jump server new')
    if (document.getElementById('id_username')) {
      document.getElementById('id_username').value = '18827266@qq.com'
      document.getElementById('password').value = '@Hh112233'
    }

    // YSNNE2JWHOV5XRC7
    if (document.getElementsByName('code').length > 0) {
      document.getElementsByName('code')[0].value = G.generate('YSNNE2JWHOV5XRC7')
    }
    return true
  },
}

let actions = {
  addAllLine: _addAllLine,
  customScript: _customScript,
  removeAllLine: _removeAllLine,
  updatePassword: _updatePassword,
}

console.log('content-script load')

// 监听指令
function handleMessage(data, sender, back) {
  console.log('监听消息--->', data, sender, back)
  actions[data.action](data.params, back)

  return true
}
chrome.runtime.onMessage.addListener(handleMessage)

// 页面自动化调整
var url = document.URL
var isMatchRule = false

// 特定web站点处理
for (let rule in rules) {
  // console.log(`try to match: ${rule}`)
  if (url.indexOf(rule) > -1) {
    console.log(`-----------------------------------------------------`)
    console.log(`${rule} is match!`)
    console.log(`-----------------------------------------------------`)
    rules[rule]()
    isMatchRule = true
    break
  }
}

// 规则外的页面
if (!isMatchRule) normalProcess(url)
